Ext.define('HRMS.controller.user.AccountController', {
    extend: 'Ext.app.Controller',

    stores: [
         'user.Account'
    ],
   
    models:[
         'user.Account'
    ],
         
    views: [
        'user.AccountList',
        'user.AddAccount',
        'user.EditAccount'
    ],
    
    refs: [         
         {ref: 'accountList', selector: 'accountlist #accountgrid'}
    ],
    
    init: function() {
        this.control({
        	'accountlist #accountgrid button[action=add]' : {
        		click: this.onAddAccount
        	},
        	'accountlist #accountgrid': {
                itemdblclick: this.onEditAccount
            },
        	'accountlist #accountgrid button[action=delete]' : {
        		click: this.onDeleteAccount
        	},
        	'editaccount button[action=save]' : {
        		click: this.onUpdateAccount
        	}
        });
    },
    
    onAddAccount: function(){
    	this.onEditAccount();
    },
    
    onEditAccount: function(grid, record){    	
    	var edit = Ext.create('HRMS.view.user.EditAccount').show();
    	if(record){
    		edit.down('form').loadRecord(record);
    	}    	
    },
    
    onDeleteAccount: function(){
    	var grid = this.getAccountList(),
    		store = this.getUserAccountStore();
    		selection = grid.getSelectionModel().getSelection()[0];
    	
    	if(selection){
    		Ext.Msg.confirm('Delete', 'Are you sure?', function(buttonText) {			
    			if (buttonText == "yes") {
    				store.remove(selection); 
    				store.sync();
    			}
        	});
    	}    	
    },
    
    onUpdateAccount: function(button){
    	var win    = button.up('window'),
        	form   = win.down('form'),
        	record = form.getRecord(),
        	values = form.getValues();
    
		if (values.id > 0){
			record.set(values);
		} else {
			record = Ext.create('HRMS.model.user.Account');
			record.set(values);
			this.getUserAccountStore().add(record);
		}

		win.close();
		this.getUserAccountStore().sync();    	
    }
});
